// src/stores/modules/app.ts
import { store } from './index'
import { defineStore } from 'pinia'
import { getAccessToken } from '@/utils/auth'
import { useAppStoreHook } from '@/stores/modules/app'

interface UserInfo {
  id?: string | number
  name?: string
  avatar?: string
  [key: string]: any // 保留其他扩展字段
}

// 1.（状态类型）
interface AppState {
  userInfo: UserInfo
}

export const useStoreApp = defineStore('app', {
  state: (): AppState => ({
    userInfo: {},
  }),

  getters: {
    /**
     * 获取用户信息
     */
    getUserInfo(): UserInfo {
      if (this.userInfo.id !== undefined) return this.userInfo
      // 处理localStorage为null的情况
      const localUserInfo = localStorage.getItem('userInfo')
      return localUserInfo ? JSON.parse(localUserInfo).userInfo : {}
    },
  },

  actions: {
    /**
     * 设置完整的用户信息
     * @param info 用户信息对象
     */

    async setUserInfoAction(info) {
      if (!getAccessToken()) {
        return null
      }
      let data = info || JSON.parse(localStorage.getItem('userInfo'))
      console.log('userInfo', data)
      this.userInfo = data.userInfo
      console.log('permissions', this.permissions)
      //3.存储权限信息
      this.setUserInfo(data.userInfo) //存储用户信息
      localStorage.setItem('userInfo', JSON.stringify(data))
    },

    /**
     * 清除用户数据和权限（用于退出登录）
     */
    clearUserData() {
      this.userInfo = {}
      console.log('1userInfo,')
      localStorage.removeItem('userInfo')
    }
  },

  persist: false
})

export function useAppStoreHook() {
  return useStoreApp(store)
}
